﻿using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Reflection;

namespace Bot.Domain.DialogFlow
{
    public class PropertyIgnoreSerializerContractResolver : CamelCasePropertyNamesContractResolver
    {
        private Dictionary<Type, HashSet<string>> _ignores;

        public PropertyIgnoreSerializerContractResolver() : base()
        {
            _ignores = new Dictionary<Type, HashSet<string>>();
        }

        public void IgnoreProperty(Type type, params string[] names)
        {
            if (!_ignores.ContainsKey(type))
            {
                _ignores[type] = new HashSet<string>();
            }
            foreach(var prop in names)
            {
                _ignores[type].Add(prop);
            }
        }

        private bool IsIgnored(Type type, string name)
        {
            if (!_ignores.ContainsKey(type)) return false;
            return _ignores[type].Contains(name);
        }

        protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
        {
            var property =  base.CreateProperty(member, memberSerialization);
            if (IsIgnored(property.DeclaringType, property.PropertyName))
            {
                property.ShouldSerialize = i => false;
            }
            return property;
        }
    }
}
